package ru.shadieq.finance.tracker.persistent.dao.impl;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;
import ru.shadieq.finance.tracker.persistent.dao.BaseDao;

import java.io.Serializable;

/**
 * Created by Shadieq on 14.12.2014.
 */
@Transactional
public abstract class AbstractHibernateBaseDao<ENTITY, KEY extends Serializable> implements BaseDao<ENTITY, KEY> {
    private SessionFactory sessionFactory;

    private Class<ENTITY> clazz;

    @Override
    public void add(ENTITY entity) {
        getSession().persist(entity);
    }

    @Override
    public void delete(ENTITY entity) {
        getSession().delete(entity);
    }

    @Override
    @SuppressWarnings("unchecked")
    public ENTITY get(KEY id) {
        return (ENTITY) getSession().get(clazz, id);
    }

    @Override
    public void update(ENTITY entity) {
        getSession().saveOrUpdate(entity);
    }

    protected Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public final void setClass(Class<ENTITY> clazz) {
        this.clazz = clazz;
    }
}
